<script setup>
import {onMounted, reactive, ref} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import {Plus} from "@element-plus/icons-vue";

const formInline = reactive({
  courseName: '',
  typeId: '',      // 添加课程类型搜索
  teacherId: '',   // 添加教师ID搜索
  teacherName: '', // 添加教师姓名搜索
  pageNum: 1,
  pageSize: 3
})

const total = ref(0)
const isAdd = ref(true)
const saveOrUpdateVisible = ref(false)
const saveOrUpdateTitle = ref('添加')
const fileList = ref([])
const imageUrl = ref('')
const videoFileList = ref([])  // 添加视频文件列表
const videoUrl = ref('')      // 添加视频URL
const multipleSelection = ref([])
const formLabelWidth = '120px'
const courseTypes = ref([])
const teacherList = ref([])  // 添加老师列表变量

const course = ref({
  id: '',                    // 编号
  courseName: '',            // 课程名称
  courseintroduce: '',       // 课程简介
  teacherId: '',             // 教师ID
  teacherName: '',           // 教师名称
  tabularChart: '',          // 课程图片
  courseDetails: '',         // 课程详情
  viewCount: '',            // 观看数
  courseTime: '',           // 课程时间
  courseVideo: '',          // 课程视频
  applicablePopulation: '', // 适用人群
  collects: '',            // 收藏数
  courseMount: '',         // 课程数量
  discountedPrice: '',    // 优惠价格
  expirationDate: '',     // 有效期
  learnHarvest: '',       // 学习收获
  originalPrice: '',      // 原价
  pjCount: '',           // 评价数量
  subscriptionNotice: '', // 订阅提示
  typeId: '',            // 类型ID
  typeName: '',          // 类型名称
  xueCount: ''          // 学习人数
})

// 在 course 变量定义后添加 course2
const course2 = ref({
  id: '',                         // 编号
  coursename: '',                 // 课程名称
  courseintroduce: '',           // 课程简介
  teacherId: '',                 // 教师ID，保持大写
  tabularchart: '',              // 课程图片
  coursetime: '',                // 课程时间
  coursevideo: '',               // 课程视频
  applicablepopulation: '',      // 适用人群
  collects: '',                  // 收藏数
  coursemount: '',               // 课程数量
  discountedprice: '',          // 优惠价格
  expirationdate: '',           // 有效期
  learnharvest: '',             // 学习收获
  originalprice: '',            // 原价
  pjcount: '',                  // 评价数量
  subscriptionnotice: '',        // 订阅提示
  typeId: '',                   // 类型ID，保持大写
  xuecount: ''                  // 学习人数
})

// 获取课程类型数据
const getCourseTypes = () => {
  console.log('开始获取课程类型...')
  axios.get('/vCourse/getType')
    .then(res => {
      console.log('获取课程类型响应数据：', res.data)
      if (res.data.code === 1) {
        courseTypes.value = res.data.data
        console.log('课程类型数据已保存：', courseTypes.value)
      } else {
        console.error('获取课程类型失败：', res.data.msg)
        ElMessage.error(res.data.msg || '获取课程类型失败')
      }
    })
    .catch(err => {
      console.error('获取课程类型失败：', err)
      ElMessage.error('获取课程类型失败')
    })
}

// 获取老师列表
const getTeacherList = () => {
  console.log('开始获取老师列表...')
  axios.get('/vCourse/getConsult')
    .then(res => {
      console.log('获取老师列表响应数据：', res.data)
      if (res.data.code === 1) {
        teacherList.value = res.data.data
      } else {
        ElMessage.error(res.data.msg || '获取老师列表失败')
      }
    })
    .catch(err => {
      console.error('获取老师列表失败：', err)
      ElMessage.error('获取老师列表失败')
    })
}

// 根据类型ID获取类型名称
const getTypeName = (typeId) => {
  if (!typeId) return '未设置'
  const type = courseTypes.value.find(t => Number(t.id) === Number(typeId))
  return type ? type.name : '未知类型'
}

// 获取课程列表数据
const getCourseList = () => {
  axios.get('/vCourse/getCourseByPage', {
    params: formInline
  })
  .then(res => {
    console.log('获取课程列表响应数据：', {
      code: res.data.code,
      msg: res.data.msg,
      total: res.data.data.total,
      list: res.data.data.list
    })
    total.value = res.data.data.total
    // 处理每条数据，添加类型名称
    tableData.value = res.data.data.list.map(item => ({
      ...item,
      typeName: getTypeName(item.typeId)
    }))
  })
  .catch(err => {
    console.error('获取课程列表失败：', err)
  })
}

// 搜索
const onSubmit = () => {
  formInline.pageNum = 1
  getCourseList()
}

// 重置搜索
const onReset = () => {
  formInline.courseName = ''
  formInline.typeId = ''
  formInline.teacherId = ''
  formInline.teacherName = ''
  formInline.pageNum = 1
  getCourseList()
}

// 分页
const handleSizeChange = (val) => {
  formInline.pageSize = val
  formInline.pageNum = 1
  getCourseList()
}

const handleCurrentChange = (val) => {
  formInline.pageNum = val
  getCourseList()
}

// 添加多选相关方法
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 修改
const onEdit = row => {
  saveOrUpdateTitle.value = '编辑'
  saveOrUpdateVisible.value = true
  course.value = { 
    ...row,
    typeName: getTypeName(row.typeId)
  }
  
  // 转换数据到 course2
  course2.value = {
    id: row.id,
    coursename: row.courseName,
    courseintroduce: row.courseintroduce,
    teacherId: row.teacherId,
    tabularchart: row.tabularChart,
    coursetime: row.courseTime,
    coursevideo: row.courseVideo,
    applicablepopulation: row.applicablePopulation,
    collects: row.collects,
    coursemount: row.courseMount,
    discountedprice: row.discountedPrice,
    expirationdate: row.expirationDate,
    learnharvest: row.learnHarvest,
    originalprice: row.originalPrice,
    pjcount: row.pjCount,
    subscriptionnotice: row.subscriptionNotice,
    typeId: row.typeId,
    xuecount: row.xueCount
  }
  
  // 初始化图片列表
  const images = row.tabularChart?.split(',').filter(Boolean) || []
  fileList.value = images.map(img => ({
    name: img,
    url: loacalUrl + img
  }))

  // 初始化视频
  if (row.courseVideo) {
    videoFileList.value = [{
      name: row.courseVideo,
      url: loacalUrl + row.courseVideo
    }]
    videoUrl.value = loacalUrl + row.courseVideo
  } else {
    videoFileList.value = []
    videoUrl.value = ''
  }

  // 显示最后一张图片
  imageUrl.value = images.length > 0 ? loacalUrl + images[images.length - 1] : ''
  isAdd.value = false
}

// 去添加页面
const onAdd = async () => {
  saveOrUpdateTitle.value = '添加'
  saveOrUpdateVisible.value = true
  
  // 重置表单数据
  course.value = {
    id: '',
    courseName: '',
    courseintroduce: '',
    teacherId: '',
    teacherName: '',
    tabularChart: '',
    courseDetails: '',
    viewCount: '',
    courseTime: '',
    courseVideo: '',
    applicablePopulation: '',
    collects: '',
    courseMount: '',
    discountedPrice: '',
    expirationDate: '',
    learnHarvest: '',
    originalPrice: '',
    pjCount: '',
    subscriptionNotice: '',
    typeId: '',
    typeName: '',
    xueCount: ''
  }
  
  // 清空 course2
  course2.value = {
    id: '',
    coursename: '',
    courseintroduce: '',
    teacherId: '',
    tabularchart: '',
    coursetime: '',
    coursevideo: '',
    applicablepopulation: '',
    collects: '',
    coursemount: '',
    discountedprice: '',
    expirationdate: '',
    learnharvest: '',
    originalprice: '',
    pjcount: '',
    subscriptionnotice: '',
    typeId: '',
    xuecount: ''
  }
  fileList.value = []
  videoFileList.value = []
  videoUrl.value = ''
  isAdd.value = true
}

// 取消
const closeCourse = () => {
  saveOrUpdateVisible.value = false
  imageUrl.value = ''
  fileList.value = []
  videoFileList.value = []
  videoUrl.value = ''
}

// 保存（添加和修改）
const saveCourse = () => {
  // 在提交前，将 course 的值同步到 course2
  if (saveOrUpdateTitle.value === '添加') {
    course2.value = {
      ...course2.value,
      courseintroduce: course.value.courseintroduce,
      applicablepopulation: course.value.applicablePopulation,
      typeId: Number(course.value.typeId),  // 使用大写的 typeId
      learnharvest: course.value.learnHarvest,
      subscriptionnotice: course.value.subscriptionNotice,
      collects: course.value.collects,
      teacherId: course.value.teacherId,    // 使用大写的 teacherId
      coursevideo: course.value.courseVideo,
      pjcount: course.value.pjCount,
      xuecount: course.value.xueCount,
      originalprice: course.value.originalPrice,
      discountedprice: course.value.discountedPrice,
      expirationdate: course.value.expirationDate,
      coursename: course.value.courseName,
      tabularchart: course.value.tabularChart,  // 使用小写的tabularchart
      coursetime: course.value.courseTime,
      coursemount: course.value.courseMount
    }

    console.log('添加课程的参数：', course2._rawValue)

    axios.post('/vCourse/addCourse?1', course2._rawValue)
      .then(res => {
        if(res.data.code === 1) {
          getCourseList()
          ElMessage({
            message: '添加成功！',
            type: 'success',
          })
          saveOrUpdateVisible.value = false
        } else {
          ElMessage({
            message: res.data.msg || '添加失败！',
            type: 'error',
          })
        }
      })
      .catch(err => {
        console.log('err', err)
        ElMessage({
          message: '添加失败！',
          type: 'error',
        })
      })
  } else if (saveOrUpdateTitle.value === '编辑') {
    course2.value = {
      ...course2.value,
      id: course.value.id,
      courseintroduce: course.value.courseintroduce,
      applicablepopulation: course.value.applicablePopulation,
      typeId: course.value.typeId,
      learnharvest: course.value.learnHarvest,
      subscriptionnotice: course.value.subscriptionNotice,
      collects: course.value.collects,
      teacherId: course.value.teacherId,
      coursevideo: course.value.courseVideo,
      pjcount: course.value.pjCount,
      xuecount: course.value.xueCount,
      originalprice: course.value.originalPrice,
      discountedprice: course.value.discountedPrice,
      expirationdate: course.value.expirationDate,
      coursename: course.value.courseName,
      tabularchart: course.value.tabularChart,  // 使用小写的tabularchart
      coursetime: course.value.courseTime,
      coursemount: course.value.courseMount
    }

    console.log('修改课程的参数：', course2.value)

    axios.put('/vCourse/updateCourse', course2._rawValue)
      .then(res => {
        if(res.data.code === 1) {
          getCourseList()
          ElMessage({
            message: res.data.msg || '修改成功！',
            type: 'success',
          })
          saveOrUpdateVisible.value = false
        } else {
          ElMessage({
            message: res.data.msg || '修改失败！',
            type: 'error',
          })
        }
      })
      .catch(err => {
        console.error('修改课程失败：', err)
        ElMessage({
          message: '修改失败！',
          type: 'error',
        })
      })
  }
}

// 删除
const onDel = id => {
  ElMessageBox.confirm(
    '确定要删除这条课程记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios.delete('/vCourse/deleteCourse', {
      params: { id: id }
    })
    .then(res => {
      getCourseList()
      ElMessage({
        message: '删除成功！',
        type: 'success',
      })
    })
    .catch(err => {
      console.log('err', err)
      ElMessage({
        message: '删除失败！',
        type: 'error',
      })
    })
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请至少选择一条记录'
    })
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    const params = new URLSearchParams()
    ids.forEach(id => params.append('ids', id))
    
    axios.delete(`/vCourse/deleteCourseBatch?${params.toString()}`)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '批量删除成功'
      })
      getCourseList() // 刷新列表
    })
    .catch(err => {
      console.log('err', err)
      ElMessage({
        type: 'error',
        message: '批量删除失败'
      })
    })
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const tableData = ref()

const loacalUrl = 'http://localhost:8080/file/downLoad?fileName='
// 图片上传成功
const handleAvatarSuccess = (res, file) => {
  if(isAdd.value) {
    // 添加模式,直接赋值
    course.value.tabularChart = res.data
    course2.value.tabularchart = res.data
    imageUrl.value = URL.createObjectURL(file.raw)
  } else {
    // 修改模式,追加图片并更新最后一张
    const images = course.value.tabularChart ? course.value.tabularChart.split(",").filter(Boolean) : []
    images.push(res.data)
    const newTabularChart = images.join(",")
    course.value.tabularChart = newTabularChart
    course2.value.tabularchart = newTabularChart  // 使用小写的tabularchart
    imageUrl.value = loacalUrl + res.data
  }
}

// 移除文件处理
const handleRemove = (file, fileList) => {
  if (isAdd.value) {
    course.value.tabularChart = ''
    course2.value.tabularchart = ''
    imageUrl.value = ''
  } else {
    // 过滤出剩余的图片并更新最后一张
    const remainFiles = fileList.map(f => f.response?.data || f.name).filter(Boolean)
    const newTabularChart = remainFiles.join(',')
    course.value.tabularChart = newTabularChart
    course2.value.tabularchart = newTabularChart  // 使用小写的tabularchart
    imageUrl.value = remainFiles.length > 0
      ? loacalUrl + remainFiles[remainFiles.length - 1]
      : ''
  }
}

// 视频上传成功
const handleVideoSuccess = (res, file) => {
  if(isAdd.value) {
    // 添加模式,直接赋值
    course.value.courseVideo = res.data
    course2.value.coursevideo = res.data
    videoUrl.value = URL.createObjectURL(file.raw)
  } else {
    // 修改模式,直接替换
    course.value.courseVideo = res.data
    course2.value.coursevideo = res.data
    videoUrl.value = loacalUrl + res.data
  }
}

// 视频移除处理
const handleVideoRemove = () => {
  course.value.courseVideo = ''
  course2.value.coursevideo = ''
  videoUrl.value = ''
  videoFileList.value = []
}

// 页面加载时获取数据
onMounted(() => {
  console.log('页面加载了')
  getCourseTypes()  // 获取课程类型
  getCourseList()   // 获取课程列表
  getTeacherList()  // 获取老师列表
})
</script>

<template>
  <div class="course-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="课程名称">
        <el-input v-model="formInline.courseName" placeholder="请输入课程名称" clearable />
      </el-form-item>

      <el-form-item label="课程类型">
        <el-select v-model="formInline.typeId" placeholder="请选择课程类型" clearable style="width: 240px;">
          <el-option
            v-for="type in courseTypes"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="教师">
        <el-select v-model="formInline.teacherId" placeholder="请选择教师" clearable style="width: 240px;">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="'ID:' + teacher.id + ' - ' + teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

  
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <div class="toolbar" style="margin-bottom: 16px">
      <el-button @click="onAdd" type="primary" icon="Plus" plain>新增</el-button>
      <el-button type="danger" icon="Delete" plain @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="编号" width="80" />
      <el-table-column prop="courseName" label="课程名称" width="120" />
      <el-table-column prop="typeName" label="课程类型" width="120" />
      <el-table-column prop="courseintroduce" label="课程简介" width="150">
        <template #default="scope">
          <el-text :truncated="true">{{ scope.row.courseintroduce }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="teacherName" label="教师名称" width="100" />
      <el-table-column prop="tabularChart" label="课程图片" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.tabularChart"
            style="width: 100px; height: 100px"
            :src="loacalUrl + scope.row.tabularChart.split(',')[0]"
            :preview-src-list="scope.row.tabularChart.split(',').map(img => loacalUrl + img)"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="courseTime" label="课程时长" width="100" />
      <el-table-column prop="applicablePopulation" label="适用人群" width="120" />
      <el-table-column prop="discountedPrice" label="优惠价" width="100" />
      <el-table-column prop="originalPrice" label="原价" width="100" />
      <el-table-column prop="courseMount" label="课程数量" width="100" />
      <el-table-column prop="collects" label="收藏数" width="100" />
      <el-table-column prop="pjCount" label="评价数" width="100" />
      <el-table-column prop="xueCount" label="学习人数" width="100" />
      
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            size="small" 
            @click="onEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button 
            link 
            type="primary" 
            size="small" 
            @click="onDel(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="formInline.pageNum"
      v-model:page-size="formInline.pageSize"
      :page-sizes="[3, 5, 10, 20]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑弹框 -->
    <el-dialog
      v-model="saveOrUpdateVisible"
      :title="saveOrUpdateTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="course" label-width="120px">
        <el-form-item label="课程名称">
          <el-input v-model="course.courseName" placeholder="请输入课程名称" />
        </el-form-item>

        <el-form-item label="课程类型">
          <el-select v-model="course.typeId" placeholder="请选择课程类型">
            <el-option
              v-for="type in courseTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="授课老师">
          <el-select v-model="course.teacherId" placeholder="请选择授课老师">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="'ID:' + teacher.id + ' - ' + teacher.name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程简介">
          <el-input 
            v-model="course.courseintroduce" 
            type="textarea" 
            placeholder="请输入课程简介"
          />
        </el-form-item>

        <el-form-item label="课程图片">
          <el-upload
            v-model:file-list="fileList"
            class="avatar-uploader"
            list-type="picture-card"
            action="http://localhost:8080/file/upload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :limit="isAdd ? 1 : Infinity"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="课程视频">
          <el-upload
            v-model:file-list="videoFileList"
            class="video-uploader"
            action="http://localhost:8080/file/upload"
            :on-success="handleVideoSuccess"
            :on-remove="handleVideoRemove"
            :limit="1"
            accept=".mp4,.avi,.mov"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 mp4/avi/mov 格式视频</div>
            </template>
          </el-upload>
          <video v-if="videoUrl" :src="videoUrl" controls style="max-width: 100%; margin-top: 10px;"></video>
        </el-form-item>

        <el-form-item label="课程时长">
          <el-input v-model="course.courseTime" placeholder="请输入课程时长" />
        </el-form-item>

        <el-form-item label="适用人群">
          <el-input v-model="course.applicablePopulation" placeholder="请输入适用人群" />
        </el-form-item>

        <el-form-item label="优惠价格">
          <el-input v-model="course.discountedPrice" placeholder="请输入优惠价格" />
        </el-form-item>

        <el-form-item label="原价">
          <el-input v-model="course.originalPrice" placeholder="请输入原价" />
        </el-form-item>

        <el-form-item label="课程数量">
          <el-input v-model="course.courseMount" placeholder="请输入课程数量" />
        </el-form-item>

        <el-form-item label="有效期(天)">
          <el-input v-model="course.expirationDate" placeholder="请输入有效期" />
        </el-form-item>

        <el-form-item label="学习收获">
          <el-input 
            v-model="course.learnHarvest" 
            type="textarea"
            placeholder="请输入学习收获" 
          />
        </el-form-item>

        <el-form-item label="订阅提示">
          <el-input 
            v-model="course.subscriptionNotice" 
            type="textarea"
            placeholder="请输入订阅提示" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCourse">取消</el-button>
          <el-button type="primary" @click="saveCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.course-container {
  padding: 20px;
}

.demo-form-inline .el-form-item {
  margin-right: 16px;
}

.toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: none;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.el-button + .el-button {
  margin-left: 8px;
}

.video-uploader {
  margin-bottom: 10px;
}

.video-uploader .el-upload {
  width: 100%;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>